package com.css.bjdt_core.importExport.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPOutputStream;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.TableName;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.bjdt_core.importExport.entity.CellDataValueIE;
import com.css.bjdt_core.importExport.entity.DnDzzIE;
import com.css.bjdt_core.importExport.entity.MsgCenter;
import com.css.bjdt_core.importExport.entity.RptBatchDzzRelIE;
import com.css.bjdt_core.importExport.entity.RptBatchIE;
import com.css.bjdt_core.importExport.entity.RptBatchUnitRelIE;
import com.css.bjdt_core.importExport.entity.RptUnitAnnualRelIE;
import com.css.bjdt_core.importExport.entity.RptUnitIE;
import com.css.bjdt_core.importExport.entity.WrapObject;
import com.css.bjdt_core.reportPrepare.entity.RptUnit;
import com.css.bjdt_core.reportPrepare.service.RptUnitService;
import com.css.bjdt_core.util.CommonUtil;
import com.css.bjdt_core.util.FileUtils;
import com.css.bjdt_core.util.ReportConstant;

@Service
public class DataExportService {

	@Autowired
	private Dao dao;

	@Autowired
	private RptUnitService rptUnitService;

	public String exportReport(String folderPath, String annualId, String dzzId, String batchId) {
		//根据党组织ID获得当前单位ID
		RptUnit rptUnit = rptUnitService.queryByDzzIdAndAnnualId(dzzId, annualId);
		// 判断路径是否存在
		File folder = new File(folderPath);
		byte[] encArray = null;
		if (!folder.exists()) {
			return "路径不存在，请正确选择。";
		}

		// 消息对象
		final MsgCenter msgCenter = new MsgCenter();

		// 包装对象
		WrapObject wrap = new WrapObject();

		// 转换数据
		boolean isOK = false;
		try {
			// 其它无特殊处理的表
			String[] nameArray = CommonUtil.readPropertiesExportTable().split("\\|");
			TableName.set(annualId);
			for (String name : nameArray) {
				String nameNew = name.replace("ANNUALID", annualId);
				List<Record> dataList = new ArrayList<Record>();
				if (rptUnit.getUnitType().equals("1")) {
					//非汇总单位
					if (name.toUpperCase().indexOf("RPT_EXPL_TEXT") == 0)
						dataList = dao.query(nameNew, Cnd.where("dzz_id", "=", dzzId), null);
					else
						dataList = dao.query(nameNew, Cnd.where("dzz_id", "=", dzzId).and("sum_status", "is", null),
								null);
				} else {
					//汇总单位
					if (name.toUpperCase().indexOf("RPT_EXPL_TEXT") == 0)
						dataList = dao.query(nameNew, Cnd.where("dzz_id", "=", dzzId), null);
					else
						dataList = dao.query(nameNew, Cnd.where("dzz_id", "=", dzzId).and("sum_status", "=", 1), null);
				}
				wrap.putData(nameNew, dataList);
			}
			List<Record> rptBatchTemplateRList = dao.query("rpt_batch_template_r", Cnd.where("batch_id", "=", batchId),
					null);
			wrap.putData("rpt_batch_template_r", rptBatchTemplateRList);

			//需要特殊处理的表,这里面只保存单个实体就行，因为每个单位只有一条记录
			//塞单位信息
			wrap.setRptUnitIE(dao.fetch(RptUnitIE.class, Cnd.where("ID", "=", rptUnit.getId())));
			//塞党组织信息
			wrap.setDnDzzIE(dao.fetch(DnDzzIE.class, Cnd.where("DZZID", "=", dzzId)));
			//塞党组织ID
			wrap.setDzzId(dzzId);
			//塞批次信息
			wrap.setRptBatchIE(dao.fetch(RptBatchIE.class, Cnd.where("BATCH_ID", "=", batchId)));
			//批次和党组织之间的关系
			wrap.setRptBatchDzzRelIE(dao.fetch(RptBatchDzzRelIE.class, Cnd.where("BATCH_ID", "=", batchId)));
			//单位和批次信息表
			wrap.setRptBatchUnitRelIE(dao.fetch(RptBatchUnitRelIE.class, Cnd.where("BATCH_ID", "=", batchId)));
			//单位年度党组织表
			wrap.setRptUnitAnnualRelIE(dao.fetch(RptUnitAnnualRelIE.class, Cnd.where("ANNUAL_ID", "=", annualId)
					.and("UNIT_ID", "=", rptUnit.getId()).and("DZZ_ID", "=", dzzId)));
			//该单位上报哪些报表
			//wrap.setRptBatchTemplateRelIE(dao.fetch(RptBatchTemplateRelIE.class, Cnd.where("BATCH_ID", "=", batchId)));
			// 导出文件路径
			SimpleDateFormat formatterFileName = new SimpleDateFormat("yyyyMMddHHmmss");
			if (!folderPath.endsWith(File.separator)) {
				folderPath = folderPath + File.separator; // 补一个\\
			}
			String fileName = rptUnit.getFullName() + "_" + formatterFileName.format(new Date()) + ".dat";
			String filePath = folderPath + fileName;

			// 序列化
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(wrap);
			oos.close();

			// ZIP压缩
			ByteArrayOutputStream out2 = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(out2);
			baos.writeTo(gzip);
			gzip.close();

			// DES加密
			/*encArray = new DESUtil().encrypt(out2.toByteArray());
			msgCenter.putMsg("数据转换完毕。");*/

			// 写入文件
			msgCenter.putMsg("将数据写入文件（" + fileName + "）..");
			FileUtils.writeBytesToFile(new File(filePath), out2.toByteArray());
			//FileUtils.writeFile(wrap.toString(), filePath);

			return fileName;
		} catch (Error e) {
			e.printStackTrace();
			msgCenter.putMsg("---------------执行出错：---------------");
			msgCenter.putMsg(e.getMessage());
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			msgCenter.putMsg("---------------执行出错：---------------");
			msgCenter.putMsg(e.getMessage());
			return "";
		} finally {
			System.out.println(msgCenter.getAllMsg());
		}

	}

	public List<Record> getAllReportDataByDzz(String annualId, String dzzId) {
		String tableName = ReportConstant.EXECUTIVE_TABLE_PREFIX + annualId;
		Sql strSql = Sqls
				.create("select cell_data_id,cell_id,cell_value,batch_id,abs_row_num,abs_col_num,rel_row_num,rel_col_num,dzz_id,template_id,sum_status from "
						+ tableName + " where dzz_id = @dzzId");
		strSql.params().set("dzzId", dzzId);

		strSql.setCallback(new SqlCallback() {
			List<Record> list = new ArrayList<Record>();

			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql strSql) throws SQLException {
				while (rs.next()) {
					CellDataValueIE cellDataValueIE = new CellDataValueIE();
					cellDataValueIE.setCellDataId(rs.getString("cell_data_id"));
					cellDataValueIE.setCellId(rs.getString("cell_id"));
					cellDataValueIE.setCellValue(rs.getString("cell_value"));
					cellDataValueIE.setBatchId(rs.getString("batch_id"));
					cellDataValueIE.setAbsRowNum(rs.getString("abs_row_num"));
					cellDataValueIE.setAbsColNum(rs.getString("abs_col_num"));
					cellDataValueIE.setRelColNum(rs.getString("rel_col_num"));
					cellDataValueIE.setRelRowNum(rs.getString("rel_row_num"));
					cellDataValueIE.setDzzId(rs.getString("dzz_id"));
					cellDataValueIE.setTemplateId(rs.getString("template_id"));
					cellDataValueIE.setSumStatus(rs.getString("sum_status"));
				}
				return null;
			}
		});
		return null;
	}
}
